package com.smarthome.core.payment.alipay.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.smarthome.core.payment.alipay.AlipayService;

public class AlipayReqUtil {

    private final static Logger LOGGER = LoggerFactory.getLogger(AlipayService.class);

    /**
     * 生成签名结果
     *
     * @param sPara 要签名的数组
     * @return 签名结果字符串
     */
    public static String signRequestParams(Map<String, String> sPara) {
        String prestr = AlipayCore.createLinkString(sPara); // 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("[Alipay]sign request params,params:" + prestr);
        }
        String sign = "";
        if (AlipayConfig.sign_type.equals("RSA")) {
            sign = AlipayRSA.sign(prestr, AlipayConfig.private_key_encode_PKCS8, AlipayConfig.input_charset);
        }
        return sign;
    }

    /**
     * 生成要请求给支付宝的参数数组
     *
     * @param sParaTemp 请求前的参数数组
     * @return 要请求的参数数组
     */
    public static Map<String, String> buildRequestPara(Map<String, String> sParaTemp) {
        // 除去数组中的空值和签名参数
        Map<String, String> sPara = AlipayCore.paraFilter(sParaTemp);
        // 生成签名结果
        String mysign = signRequestParams(sPara);
        // 签名结果与签名方式加入请求提交参数组中
        sPara.put("sign", mysign);
        sPara.put("sign_type", AlipayConfig.sign_type);
        return sPara;
    }

    /**
     * 支付宝手机app支付请求串
     *
     * @param sParaTemp
     * @return <String>
     */
    public static String generateAlipayMobileReqStr(Map<String, String> sParaTemp) {
        Map<String, String> sPara = buildRequestPara(sParaTemp);
        try {
            String sign = sPara.get("sign");
            sign = URLEncoder.encode(sign, "UTF-8");
            sPara.put("sign", sign);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return AlipayCore.createLinkString(sPara);
    }

}
